package com.focusai.efairy.ui.activity.project;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.focusai.efairy.R;
import com.focusai.efairy.model.location.Location;
import com.focusai.efairy.model.project.ProjectItem;
import com.focusai.efairy.model.project.UpLoadProjectEntity;
import com.focusai.efairy.model.request.AddProjectRequest;
import com.focusai.efairy.model.request.PuteditProjectRequest;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.network.request.base.Request;
import com.focusai.efairy.ui.activity.location.AMapSelectLocationActivity;
import com.focusai.efairy.ui.base.SwipeBackBaseActivity;
import com.focusai.efairy.utils.ActivityUtils;

/**
 * Created by luo_guangwen on 2017/9/4.
 */

public class ProjectAddorEditActivity extends SwipeBackBaseActivity implements View.OnClickListener {
    public static final String PROJECT_ITEM = "project_item";
    public static final int REQUEST_CODE_ADRESS = 0x10;
    public static final String OPENTYPE = "opentype";
    public static final String ITEM_PROJECT = "item_project";

    private EditText editProjectName;
    private EditText editLeaderName;
    private EditText editLeaderPhone;
    private TextView editProjectAddress;
    private EditText editProjectDesc;
    private ProjectItem projectItem;
    private boolean isEdit = false;
    private Location location;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_add_project);
        initView();
        initData(projectItem);
        setDefaultValues();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

//        MenuItem menuItem = menu.add(MENU_GROUP_ID, MENU_ITEM_FILTER, 0, R.string.desc).setIcon(R.drawable.btn_desc_selector_);
//        MenuItemCompat.setShowAsAction(menuItem, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        MenuItem menuItem1 = menu.add(MENU_GROUP_ID, MENU_ITEM_ADD, 0, R.string.save).setTitle(R.string.save);
        MenuItemCompat.setShowAsAction(menuItem1, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == MENU_ITEM_ADD) {
            upLoadProject();
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void initTitte() {
        if (getIntent() != null) {
            isEdit = getIntent().getBooleanExtra(OPENTYPE, false);
            projectItem = (ProjectItem) getIntent().getSerializableExtra(PROJECT_ITEM);
        }
        if (isEdit) {
            setCenterTitleName("项目信息");
        } else {
            setCenterTitleName("新增项目");
        }
    }

    @Override
    protected void initView() {
        editProjectName = findView(R.id.edit_project_name);
        editLeaderName = findView(R.id.edit_leader_name);
        editLeaderPhone = findView(R.id.edit_leader_phone);
        editProjectAddress = findView(R.id.text_project_address);
        editProjectDesc = findView(R.id.edit_project_desc);
        findView(R.id.ll_project_address).setOnClickListener(this);
    }

    @Override
    protected void setDefaultValues() {

    }

    private boolean verify() {
        if (TextUtils.isEmpty(editProjectName.getText().toString())) {
            showToast("请输入项目的名称");
            return false;
        }
        if (TextUtils.isEmpty(editLeaderName.getText().toString())) {
            showToast("请输入项目负责人姓名");
            return false;
        }
        if (TextUtils.isEmpty(editLeaderPhone.getText().toString())) {
            showToast("请输入项目负责人手机");
            return false;
        }
        if (TextUtils.isEmpty(editProjectAddress.getText().toString()) || location == null) {
            showToast("请选择项目地址");
            return false;
        }
        return true;
    }

    private void initData(ProjectItem item) {
        if (item == null)
            return;
        editProjectName.setText(item.efairyproject_name);
        editLeaderName.setText(item.efairyproject_user_name);
        editLeaderPhone.setText(item.efairyproject_user_phonenumber);
        editProjectAddress.setText(item.efairyproject_address);
        if (!TextUtils.isEmpty(item.efairyproject_description)){
            editProjectDesc.setText(item.efairyproject_description);
        }
        location = new Location();
        location.setLatitude(item.efairyproject_location_lat);
        location.setLongitude(item.efairyproject_location_lng);
//        location.set(item.efairyproject_address);
    }

    private void upLoadProject() {
        if (!verify()) {
            return;
        }
        UpLoadProjectEntity entity = new UpLoadProjectEntity();
        entity.efairyproject_name = editProjectName.getText().toString();
        entity.efairyproject_user_name = editLeaderName.getText().toString();
        entity.efairyproject_user_phonenumber = editLeaderPhone.getText().toString();
        entity.efairyproject_description = editProjectDesc.getText().toString();
        entity.efairyproject_location_lat = location.getmLatitude();
        entity.efairyproject_location_lng = location.getmLongitude();
        entity.efairyproject_address = editProjectAddress.getText().toString();
        Request request;
        if (isEdit){
            if (projectItem == null){
                showToast("项目为空");
                finish();
                return;
            }
            entity.efairyproject_id = projectItem.efairyproject_id;
            request = new PuteditProjectRequest(entity, new Response.Listener<String>() {
                @Override
                protected void onSuccess(String response) {
                    closeSingleDialog();
                    if (!ProjectAddorEditActivity.this.isFinishing()) {
                        setResult(RESULT_OK);
                        finish();
                    }
                }

                @Override
                protected void onFail(NetworkException exception) {
                    closeSingleDialog();
                    doException(exception);
                }
            });
        }else {
            request = new AddProjectRequest(entity, new Response.Listener<String>() {
                @Override
                protected void onSuccess(String response) {
                    closeSingleDialog();
                    if (!ProjectAddorEditActivity.this.isFinishing()) {
                        setResult(RESULT_OK);
                        finish();
                    }
                }

                @Override
                protected void onFail(NetworkException exception) {
                    closeSingleDialog();
                    doException(exception);
                }
            });
        }
        showSingleDialog("正在保存数据..");
        HttpManager.getInstance().sendRequest(request);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_project_address:
                ActivityUtils.hideInputManager(getContext());
                Intent intent = new Intent(getContext(), AMapSelectLocationActivity.class);
                if (location != null) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(AMapSelectLocationActivity.KEY_SELECT_LOCATION_ITEM, location);
                    intent.putExtras(bundle);
                }
                startActivityForResult(intent, REQUEST_CODE_ADRESS);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_ADRESS:
                    if (data != null && data.getExtras() != null) {
                        location = (Location) data.getExtras().getSerializable(AMapSelectLocationActivity.KEY_SELECT_LOCATION_ITEM);
                        if (location != null) {
                            editProjectAddress.setText(location.getDetailAddress());
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
